package com.lexue.articlesync.controller;

import com.lexue.articlesync.service.FileUploadService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/upload")
@RequiredArgsConstructor
public class FileUploadController {
    
    private final FileUploadService fileUploadService;
    
    /**
     * 上传图片文件
     */
    @PostMapping("/image")
    public ResponseEntity<Map<String, Object>> uploadImage(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("文件不能为空"));
            }
            
            // 上传图片并获取Web访问路径
            String webPath = fileUploadService.uploadCoverImage(file);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "图片上传成功");
            response.put("path", webPath);
            response.put("url", fileUploadService.getFullHttpUrl(webPath));
            response.put("fileName", file.getOriginalFilename());
            response.put("fileSize", file.getSize());
            
            log.info("图片上传成功: 原文件={}, 保存路径={}", file.getOriginalFilename(), webPath);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("图片上传失败", e);
            return ResponseEntity.badRequest().body(createErrorResponse("图片上传失败: " + e.getMessage()));
        }
    }
    
    /**
     * 上传缩略图
     */
    @PostMapping("/thumbnail")
    public ResponseEntity<Map<String, Object>> uploadThumbnail(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("文件不能为空"));
            }
            
            // 上传缩略图并获取Web访问路径
            String webPath = fileUploadService.uploadThumbnail(file);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "缩略图上传成功");
            response.put("path", webPath);
            response.put("url", fileUploadService.getFullHttpUrl(webPath));
            response.put("fileName", file.getOriginalFilename());
            response.put("fileSize", file.getSize());
            
            log.info("缩略图上传成功: 原文件={}, 保存路径={}", file.getOriginalFilename(), webPath);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("缩略图上传失败", e);
            return ResponseEntity.badRequest().body(createErrorResponse("缩略图上传失败: " + e.getMessage()));
        }
    }
    
    /**
     * 上传通用文件
     */
    @PostMapping("/file")
    public ResponseEntity<Map<String, Object>> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam(defaultValue = "documents") String category) {
        try {
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body(createErrorResponse("文件不能为空"));
            }
            
            // 根据文件类型选择上传方式
            String webPath;
            String fileName = file.getOriginalFilename();
            String extension = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            
            switch (extension) {
                case "jpg":
                case "jpeg":
                case "png":
                case "gif":
                case "bmp":
                case "webp":
                    webPath = fileUploadService.uploadCoverImage(file);
                    break;
                default:
                    // 对于其他文件类型，暂时使用封面图片的保存方式
                    webPath = fileUploadService.uploadCoverImage(file);
                    break;
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "文件上传成功");
            response.put("path", webPath);
            response.put("url", fileUploadService.getFullHttpUrl(webPath));
            response.put("fileName", fileName);
            response.put("fileSize", file.getSize());
            response.put("category", category);
            
            log.info("文件上传成功: 原文件={}, 保存路径={}, 分类={}", fileName, webPath, category);
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("文件上传失败", e);
            return ResponseEntity.badRequest().body(createErrorResponse("文件上传失败: " + e.getMessage()));
        }
    }
    
    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("message", message);
        return response;
    }
}